import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
var camera
var scene
var renderer
var mouse
let w = window.innerWidth,h=window.innerHeight
let LEN = 2000
function main(){
  creatCamera()
  createRenderer()
  createGeometry()
}

function creatCamera(){
  scene = new THREE.Scene()

  camera = new THREE.PerspectiveCamera(45,w/h,1,10000)
  camera.position.z = 500
  camera.up.y = 1
  camera.lookAt(scene.position)

}
function createRenderer(){
  renderer = new THREE.WebGLRenderer()
  renderer.setSize(w,h)
  document.body.appendChild(renderer.domElement)
  
}

function createGeometry(){
  let s = 1200
  let n = s / 2
  for (let i = 0; i < LEN; i++) {
    var geometry = new THREE.BoxGeometry(10,10,10)
    var material = new THREE.MeshBasicMaterial({color:Math.random() * 0xffffff,side:THREE.DoubleSide})
    var mesh = new THREE.Mesh(geometry,material)

    mesh.position.x = Math.random() * s - n
    mesh.position.y = Math.random() * s - n
    mesh.position.z = Math.random() * s - n

    mesh.rotateX(Math.random()*360)
    mesh.rotateY(Math.random()*360)
    mesh.rotateZ(Math.random()*360)
    
    scene.add(mesh)
  }
 
}
let theta = 0
function render() {
  theta+=0.05
  camera.position.x = 500 * Math.sin(THREE.Math.degToRad(theta))
  camera.position.y = 500 * Math.sin(THREE.Math.degToRad(theta))
  camera.position.z = 500 * Math.cos(THREE.Math.degToRad(theta))

  camera.lookAt(scene.position)
  camera.updateMatrixWorld()

  renderer.render(scene, camera)
  requestAnimationFrame(render)
}
let INSERT 
function pickUp(){
  // 光线抛射类
  var raycaster = new THREE.Raycaster()
  // 光线的方向
  raycaster.setFromCamera(mouse,camera)
  //光线射到的物体
  var intersect = raycaster.intersectObjects(scene.children)

  if(intersect.length>0){
    if(INSERT != intersect[0].object){
      INSERT = intersect[0].object
      INSERT.currentHex = intersect[0].object.material.color
      INSERT.material.color = new THREE.Color(0xff0000)
    } else {
      INSERT.material.color = new THREE.Color(0xff0000)
    }  
  }else{
    INSERT && (INSERT.material.color = INSERT.currentHex)
  }
}
main()
render()
window.addEventListener('mousemove',(event)=>{
  mouse = {
    x:( event.clientX / window.innerWidth ) * 2 - 1,
    y:- ( event.clientY / window.innerHeight ) * 2 + 1
  }
  pickUp()
})
// /** --------------------鼠标控件对象--------------------- */
// let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
// controls.addEventListener("change", render); //监听鼠标、键盘事件
